<?php
namespace  App\Http\Controllers\Radius;
use  App\Http\Controllers\Controller;

use App\Manage_order_recode;
use App\Order;

use App\Teamqq;
use Illuminate\Http\Request;

use App\Common\ErrorDefine;

use App\Radacct;
use App\Radcheck;
use App\Radgroupcheck;
use App\Radreply;
use App\Radusergroup;
use App\Rad_manage;
use App\Radgroupreply;
use App\Rad_users;
use App\Rad_order;
use DB;
use App\Common\MyCrypt;
use App\Line;
use App\Agent;


use App\Http\Controllers\Radius\ModuleController;


class  AdminController extends Controller
{

    var     $module;
    private  $page_size;
    private  $page_no;
    private  $start_date;
    private  $end_date;
    private  $order_name;
    private  $order_value;


    public function __construct()
    {
        $this->module = new ModuleController();
    }


    /**
     * @param Request $request
     * @return string|void
     * 检测管理员状态
     */
    public function getAdminStatus(Request $request)
    {
        //        判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $token = $request->input('token');


        $manage = self::getTokenById($token);

        if(!empty($manage[0]))
        {
            $status =  'SUCCESS';
        }else{
            $status =  'FALSE';
        }

        return self::ShowMessage($status);

    }


    /**
     * @param Request $request
     * 管理员列表
     */

    public function getAdminList(Request $request)
    {
        //  判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }


        //   开户人的 token
        if(!$request->has('token') && !empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');


        //   get manage userId
        $user = self::getTokenById($token);
        if(empty($user))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }


        //  管理理员权限
        if($user[0]['level'] != 2 && $user[0]['level'] != 4)
        {
            return self::ShowError(ErrorDefine::PERMISSION_DENIED);
        }

//        switch($user[0]['level'])
//        {
//            case 2:$admin = Rad_manage::where('level','!=','2')->orderBy('created_at','desc')->get();break;
//            case 4:$admin = Rad_manage::where('belong_level',$user[0]['level'])->where('belong_manage',$user[0]['manage_id'])->orderBy('created_at','desc')->get();break;
//        }

        if($user[0]['level'] == 2 && $user[0]['manage_id'] == 9 )
        {
            $admin = Rad_manage::where('level','>','0')->get(['manage_id','username','mobile','middle-day','middle-week','middle-month','height-day','height-month','height-week','level','level','created_at','balance','ip','updated_at']);

        }else{
            switch($user[0]['level'])
            {
                case 2:$admin = Rad_manage::where('level','!=','2')->orderBy('created_at','desc')
                    ->get(['manage_id','mobile','username','middle-day','middle-week','middle-month','height-day','height-month','height-week','level','created_at','balance','ip','updated_at']);break;
                case 4:$admin = Rad_manage::where('belong_level',$user[0]['level'])->where('belong_manage',$user[0]['manage_id'])
                    ->orderBy('created_at','desc')
                    ->get(['manage_id','username','middle-day','middle-week','middle-month','height-day','height-month','height-week','level','created_at','balance','ip','updated_at']);break;
            }
        }



        $info['middle-day']  = $user[0]['middle-day'];
        $info['middle-week']  = $user[0]['middle-week'];
        $info['middle-month']  = $user[0]['middle-month'];
        $info['height-day']  = $user[0]['height-day'];
        $info['height-month']  = $user[0]['height-month'];
        $info['height-week']  = $user[0]['height-week'];
        $info['level']  = $user[0]['level'] ;


        foreach($admin as &$value)
        {
            switch($value->level)
            {
                case 1:$value->designation = '普通管理员';break;
                case 2:$value->designation = '超级管理员';break;
                case 3:$value->designation = '客服';break;
                case 4:$value->designation = '二级代理';break;
            }

        }


       $data = ['info'=>$info,'admin'=>$admin];
        return self::ShowMessage($data);

    }


    /**
     * @param Request $request
     *管理员信息修改
     */
    public function doAdminUpdate(Request $request)
    {
        $mycrypt = new  MyCrypt();

        //  判断数据是否为空
        if(empty($request->all()))
        {
            return self::ShowError(ErrorDefine::EMPTY_POST_DATA);
        }

        if(!$request->has('token') && empty($request->input('token')))
        {
            return self::ShowError(ErrorDefine::INVALID_PARAMS);

        }
        $token = $request->input('token');


        //   获取用户ID
        $user = self::getTokenById($token);

        if(!$user)
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }


        if($request->has('username') && !empty($request->input('username')) &&  strlen($request->input('username')) < 20 && strlen($request->input('username')) > 0 )
        {
            $where['username'] = $request->input('username');

        }else{
            return self::ShowError(ErrorDefine::INVALID_USERNAME);

        }


        if($request->has('password') && !empty($request->input('password')) && strlen($request->input('password')) > 0 && strlen($request->input('password')) < 20 )
        {
            $where['password']  = $mycrypt->encrypt('niumokeji-agent,'.$request->input('password'));

        }


        if($request->has('middle-day') &&  !empty($request->input('middle-day')) && $request->input('middle-day') > 0  )
        {
            $where['middle-day'] = $request->input('middle-day');

        }

        if($request->has('middle-week') && !empty($request->input('middle-week')) && $request->input('middle-week') > 0 )
        {
            $where['middle-week'] = $request->input('middle-week');
        }

        if($request->has('middle-month') && !empty($request->input('middle-month')) && $request->input('middle-month') > 0 )
        {
            $where['middle-month'] = $request->input('middle-month');

        }


        if($request->has('height-day') && !empty($request->input('height-day')) && $request->input('height-day') > 0 )
        {
            $where['height-day'] = $request->input('height-day');

        }


        if($request->has('height-week') && !empty($request->input('height-week')) && $request->input('height-week') > 0 )
        {
            $where['height-week'] = $request->input('height-week');

        }


        if($request->has('height-month') && !empty($request->input('height-month')) && $request->input('height-month') > 0 )
        {
            $where['height-month'] = $request->input('height-month');

        }


        if($request->has('manage_id') && !empty($request->input('manage_id')) && $request->input('manage_id') > 0 )
        {
            $where['manage_id'] = $request->input('manage_id');

        }else{
            return self::ShowError(ErrorDefine::INVALID_PARAMS);

        }


        if($request->has('level') && !empty($request->input('level')) && $request->input('level') > 0 )
        {
            $where['level'] = $request->input('level');
        }


        // 判断改名后的用户名i是否存在
        $manage_name = Rad_manage::where('username',$where['username'])->first();

        if($manage_name != NULL)
        {
            if ($manage_name->manage_id != $where['manage_id'])
            {
                return self::ShowError(ErrorDefine::USER_IS_EXIST);
            }

        }

        $manage = Rad_manage::find($where['manage_id']);

        if($manage == NULL)
        {
            return self::ShowError(ErrorDefine::INVALID_PARAMS);
        }

        $params = [];
        $params['manage_id'] = $where['manage_id'];

        unset($where['manage_id']);
        //  管理员信息修改权限判断

        $ret = Rad_manage::where($params)->update($where);


        if($ret)
        {
            return self::ShowMessage();
        }else{
            return self::ShowError(ErrorDefine::DATABASE_ERROR);
        }

    }




    /**
     *管理员充值
     */
    public function doAdminRecharge(Request $request)
    {
//          判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $token = $request->input('token');

        //   获取用户ID
        $user = self::getTokenById($token);


        //  检测用户权限
        if($user[0]['level'] != 2)
        {
            self::ShowError(ErrorDefine::PERMISSION_DENIED);
            return;
        }

        $manage_id = $request->input('id');
        $money = $request->input('money');

        $manage = Rad_manage::find($manage_id);

        if($money < 0 || !is_numeric($money))
        {
            return self::ShowError(ErrorDefine::INVALID_MONEY);
        }

        $manage->balance = $manage->balance + $money;

        $manage->save();

        try{
            $recode['serial_number'] = $request->input('serial_number');
            $recode['username'] = $manage->username;
            $recode['origin_type'] = $request->input('origin_type');
            $recode['pay_type'] = $request->input('pay_type');
            $recode['remark'] = '';
            $recode['contact_information'] = $request->input('contact_information');
            $recode['month'] = 1;
            $recode['order_price'] = $request->input('order_price');
            $recode['set_meal_type'] = '';
            $recode['set_meal_type_name'] = '';
            $recode['manage_id'] = $user[0]['manage_id'];
            $recode['manage_name'] = $user[0]['username'];
            $recode['days'] = 0;
            $recode['account_type'] = '代理充值';
            $recode['connect_num'] = '';
            $recode['expired_at'] = date('Y-m-d H:i:s',time());

            Manage_order_recode::insert($recode);
        }catch (\Exception $exception)
        {

        }



        return self::ShowMessage();


    }


    //  管理员删除

    public function doAdminDelete(Request $request)
    {
//        判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $token = $request->input('token');

        //   获取用户ID
        $user = self::getTokenById($token);



        if(!$request->has('manage_id') && empty($request->input('manage_id')))
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }

        $id = $request->input('manage_id');

        $manage = Rad_manage::find($id);

        if($manage == NULL)
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }

        //   判断权限

        if($user[0]['level'] != 2)
        {
            if($manage->belong_manage != $user[0]['manage_id'])
            {
                return self::ShowError(ErrorDefine::INVALID_PARAMS);
            }
        }



        Rad_manage::where('manage_id',$id)->delete();

        Rad_users::where('manage_id',$id)->update(['manage_id'=>'0']);

        if($user[0]['level'] == 2)
        {
            $qq = Teamqq::where('manage_id',$id)->get();

            if(!empty($qq))
            {
                Teamqq::where('manage_id',$id)->delete();
            }
        }


        return self::ShowMessage();
    }

    /**
     *
     * 管理员添加
     */
    public function doAdminAdd(Request $request)
    {

        $params = [];
        $qq = '';
        $qq_name = '';
        $mycrypt = new  MyCrypt();

//        判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }


        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        //   获取用户ID
        $user = self::getTokenById($token);

        if(!$request->has('username') || empty($request->input('username')))
        {
            self::ShowError(ErrorDefine::INVALID_ACCOUNT);
            return;
        }
        $params['username'] = $request->input('username');



        $users = Rad_manage::where('username',$params['username'])->get()->toArray();

        if(!empty($users))
        {
            self::ShowError(ErrorDefine::ACCOUNT_IS_EXIST);
            return;
        }

        if(!$request->has('password') || empty($request->input('password')))
        {
            self::ShowError(ErrorDefine::INVALID_POSSWORD);
            return;
        }

        $params['password'] =  $mycrypt->encrypt('niumokeji-agent,'.$request->input('password'));


        if(!$request->has('middle-day') || empty($request->input('middle-day')))
        {
            self::ShowError(ErrorDefine::INVALID_MIDDLE);
            return;
        }
        $params['middle-day'] = $request->input('middle-day');

        if(!$request->has('middle-week') || empty($request->input('middle-week')))
        {
            self::ShowError(ErrorDefine::INVALID_MIDDLE);
            return;
        }
        $params['middle-week'] = $request->input('middle-week');



        if(!$request->has('middle-month') || empty($request->input('middle-month')))
        {
            self::ShowError(ErrorDefine::INVALID_MIDDLE);
            return;
        }
        $params['middle-month'] = $request->input('middle-month');



        if(!$request->has('height-day') || empty($request->input('height-day')))
        {
            self::ShowError(ErrorDefine::INVALID_HEIGHT);
            return;
        }
        $params['height-day'] = $request->input('height-day');


        if(!$request->has('height-week') || empty($request->input('height-week')))
        {
            self::ShowError(ErrorDefine::INVALID_HEIGHT);
            return;
        }
        $params['height-week'] = $request->input('height-week');


        if(!$request->has('height-month') || empty($request->input('height-month')))
        {
            self::ShowError(ErrorDefine::INVALID_HEIGHT);
            return;
        }
        $params['height-month'] = $request->input('height-month');


        if(!$request->has('level') || empty($request->input('level')))
        {
            self::ShowError(ErrorDefine::INVALID_ADMIN_TYPE);
            return;
        }
        $params['level'] = $request->input('level');


        if($request->has('qq') && !empty($request->input('qq')))
        {
           $qq = $request->input('qq');

            $team = Teamqq::where("qq",$qq)->get()->toArray();

            if(!empty($team))
            {
                self::ShowError(ErrorDefine::ONLINETEAM_EXIST);
                return;
            }
        }


        if($request->has('qq_name') && !empty($request->input('qq_name')))
        {
            $qq_name = $request->input('qq_name');

            $team = Teamqq::where("username",$qq_name)->get()->toArray();

            if(!empty($team))
            {
                self::ShowError(ErrorDefine::ONLINETEAM_EXIST);
                return;
            }
        }

        if($user[0]['level'] == 4)
        {
            $params['belong_manage'] = $user[0]['manage_id'];
            $params['belong_level'] = $user[0]['level'];
        }



        $params['balance'] = 0;

        $id = Rad_manage::insertGetId($params);

        if($params['level'] == 4)
        {
            $manage = Rad_manage::find($id);
            $manage->belong_manage = $id;
            $manage->save();
        }

        if(!empty($qq) && !empty($qq_name))
        {

            //   初始账号  5000

            $line = [];

            $line['qq'] = $qq;
            $line['username'] = $qq_name;
            $line['manage_id'] = $id;

            $res = Teamqq::insertGetId($line);
        }


        return self::ShowMessage();

    }


    /**
     * @param Request $request
     * 管理员扣款
     */
    public function AdminDeduct(Request $request)
    {
//        判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }
        $token = $request->input('token');

        //   获取用户ID
        $user = self::getTokenById($token);

        //  检测用户权限
        if($user[0]['level'] != 2)
        {
            self::ShowError(ErrorDefine::PERMISSION_DENIED);
            return;
        }

        $manage_id = $request->input('id');
        $money = $request->input('money');

        if($money < 0 || !is_numeric($money))
        {
            return self::ShowError(ErrorDefine::INVALID_MONEY);
        }

        $manage = Rad_manage::find($manage_id);
        if($manage == NULL)
        {
            self::ShowError(ErrorDefine::INVALID_PARAMS);
            return;
        }

        if($manage->balance < $money)
        {
            self::ShowError(ErrorDefine::BALANCE_IS_LESS);
            return;
        }


        $manage->balance = $manage->balance - $money;

        $manage->save();

        return self::ShowMessage();
    }



    //  管理员开户记录数据
    public function getManageOrderRecodeData(Request $request)
    {

        $manage_code = new Manage_order_recode();




        $this->page_size = 30;
        $this->page_no = 0;
        $this->order_name = 'created_at';
        $this->order_value = 'desc';
        $this->start_date = date('Y-m-d',time());
        $this->end_date = date('Y-m-d H:i:s',time());
        $manage_id = '';

        //  判断数据是否为空
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }


        //   开户人的 token
        if(!$request->has('token') && !empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');


        //   get manage userId
        $user = self::getTokenById($token);
        if(empty($user))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }



        //  管理理员权限
        if($user[0]['level'] != 2 && $user[0]['manage_id'] != 9 )
        {
            return self::ShowError(ErrorDefine::PERMISSION_DENIED);
        }





        if($request->input('page_no'))
        {
            $this->page_no  = $request->input('page_no');
            if($this->page_no){
                $this->page_no = $this->page_no - 1;
                if(is_numeric($this->page_no)){
                    if($this->page_no<0){
                        $page_no = 0;
                    }
                }
            }
        }

        if($request->input('page_size'))
        {
            $this->page_size = $request->input('page_size');
            if($this->page_size){
                if($this->page_size <=0 ){
                    $this->page_size =  30;
                }
            }
        }


        if($request->has('start_date') && !empty($request->input('start_date')))
        {
            $this->start_date  =$request->input('start_date');

        }

        if($request->has('end_date') && !empty($request->input('end_date')))
        {
            $this->end_date  =$request->input('end_date');

        }

        //  排序
        if($request->has('order_name') && !empty($request->input('order_name')))
        {
            $this->order_name  =$request->input('order_name');
        }


        if($request->has('order_value') && !empty($request->input('order_value')))
        {
            $this->order_value  =$request->input('order_value');
        }

        if($request->has('account_type') && !empty($request->input('account_type')))
        {

            $manage_code = $manage_code->where('account_type',$request->input('account_type'));
        }

        if($request->has('pay_type') && !empty($request->input('pay_type')))
        {
            $manage_code = $manage_code->where('pay_type',$request->input('pay_type'));
        }

        if($request->has('origin_type') && !empty($request->input('origin_type')))
        {
            $manage_code = $manage_code->where('origin_type',$request->input('origin_type'));
        }

        if($request->has('status') && !empty($request->input('status')))
        {
            $manage_code = $manage_code->where('status',$request->input('status'));
        }
        if($request->has('manage_id') && !empty($request->input('manage_id')))
        {
            $manage_code = $manage_code->where('manage_id',$request->input('manage_id'));
            $manage_id = $request->input('manage_id');
        }


        $manage_code = $manage_code->where('created_at','>',$this->start_date);
        $manage_code = $manage_code->where('created_at','<',$this->end_date);
        $recode_count = $manage_code->count();

        if($manage_id)
        {
            $recode_money = Manage_order_recode::where('created_at','>',$this->start_date)
                ->where('created_at','<',$this->end_date)->where('manage_id',$manage_id)
                ->where('status',1)->sum('order_price');
        }else{
            $recode_money = Manage_order_recode::where('created_at','>',$this->start_date)
                ->where('created_at','<',$this->end_date)
                ->where('status',1)->sum('order_price');
        }


        $manage_code = $manage_code->offset($this->page_no*$this->page_size);
        $manage_code = $manage_code->limit($this->page_size);
        $manage_code = $manage_code->orderBy($this->order_name,$this->order_value);

        $recode = $manage_code->get();


        return self::ShowData($recode,$recode_count,$recode_money);

    }

    public function getSuperAdminList(Request $request)
    {
        $super = Rad_manage::where('level',2)->get(['manage_id','username']);

        return self::ShowMessage($super);
    }


    //  获取流水号
    public function getSerialNumber()
    {

        $number = self::serialNumber();

        return self::ShowMessage($number);
        
    }


    static function serialNumber()
    {
        $number = date('Ymd',time()).'00001';

        $order_number = Manage_order_recode::where('serial_number',$number)->first();

        if($order_number != NULL)
        {
            $order_number = Manage_order_recode::where('serial_number','like',date(date('Ymd',time())).'%')->orderBy('created_at','desc')->first();
            $number =  $order_number->serial_number + 1;
        }
        return $number;
    }



    static function getTokenById($token)
    {
        $user = Rad_manage::where('token',$token)->get()->toArray();
        return $user;
    }





}


